package com.wjjun.library.widget.dropdown;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.wjjun.library.R;

import java.util.ArrayList;
import java.util.List;


/**
 * dropDownMenu 弹窗内容容器，需要搭配BaseMenuTabView使用。
 * BaseMenuTabView为菜单的item，负责提供弹窗内容。
 * 已提供ListMenuTabView、GridMenuTabView。
 * BaseMenuTabView可以使用任意ViewGroup进行布局。
 * 需调用setTabLayout将包含BaseMenuTabView的布局传入，支持嵌套。
 * <p>
 * Created by wjjun on 2018/5/21.
 */
public class DropDownView extends FrameLayout {

    //底部容器，包含popupMenuViews，maskView
    private FrameLayout containerView;
    //弹出菜单父布局
    private FrameLayout popupMenuViews;

    //遮罩颜色
    private int maskColor = 0x88888888;
    private int maxHeight = 0;
    private int marginBtm = 0;

    //tabMenuView里面选中的tab位置，-1表示未选中
    private int currentTabIndex = -1;

    private List<BaseMenuTabView> tabs = new ArrayList<>();

    public DropDownView(Context context) {
        super(context, null);
    }

    public DropDownView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DropDownView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DropDownView);
        maskColor = a.getColor(R.styleable.DropDownView_ddv_maskColor, maskColor);
        maxHeight = a.getDimensionPixelOffset(R.styleable.DropDownView_ddv_maxHeight, 0);
        marginBtm = a.getDimensionPixelOffset(R.styleable.DropDownView_ddv_content_margin_btm, 0);
        a.recycle();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initContainerView();
    }

    private void initContainerView() {
        //初始化containerView并将其添加到DropDownMenu
        containerView = new FrameLayout(getContext());

        containerView.setBackgroundColor(maskColor);
        containerView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                closeMenu();
            }
        });
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        addView(containerView, params);

        popupMenuViews = new FrameLayout(getContext());
        popupMenuViews.setBackgroundColor(Color.WHITE);
        popupMenuViews.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams
                .MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.bottomMargin = marginBtm;
        popupMenuViews.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int height = popupMenuViews.getHeight();
                if (height > maxHeight && maxHeight > 0) {
                    popupMenuViews.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams
                            .MATCH_PARENT, maxHeight));
                }
            }
        });
        containerView.addView(popupMenuViews, layoutParams);

        containerView.setVisibility(GONE);
        popupMenuViews.setVisibility(GONE);
    }

    public void setTabLayout(ViewGroup viewGroup) {
        tabs.clear();
        findMenuTab(viewGroup);
        for (BaseMenuTabView item : tabs) {
            item.bindDropDownView(this);
            item.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    switchMenu(tabs.indexOf(item));
                }
            });
        }
    }

    private void findMenuTab(ViewGroup view) {
        int size = view.getChildCount();
        for (int i = 0; i < size; i++) {
            View item = view.getChildAt(i);
            if (item instanceof ViewGroup) {
                findMenuTab((ViewGroup) item);
            } else if (item instanceof BaseMenuTabView) { //tab项
                tabs.add((BaseMenuTabView) item);
            }
        }
    }


    /**
     * DropDownMenu是否处于可见状态
     */
    public boolean isShowing() {
        return popupMenuViews.getVisibility() == VISIBLE;
    }

    /**
     * 切换菜单
     */
    private void switchMenu(int index) {
        if (index < 0 || index >= tabs.size()) {
            return;
        }
        if (currentTabIndex == index && isShowing()) {
            closeMenu();
        } else {
            openMenu(index);
        }
    }

    /**
     * 关闭菜单
     */
    public void closeMenu() {
        notifyMenuItemChange(currentTabIndex, false);

        popupMenuViews.setVisibility(View.GONE);
        popupMenuViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim
                .anim_menu_out));
        containerView.setVisibility(GONE);
        containerView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_mask_out));
    }


    private void openMenu(int index) {
        BaseMenuTabView tabView = tabs.get(index);
        View view = null;
        if (tabView != null) {
            view = tabView.getContentView();
        }

        if (view == null) {
            return;
        }
        if (currentTabIndex != index) {
            notifyMenuItemChange(currentTabIndex, false);
        }
        currentTabIndex = index;
        notifyMenuItemChange(index, true);

        popupMenuViews.removeAllViews();
        popupMenuViews.setVisibility(View.VISIBLE);
        popupMenuViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R
                .anim.anim_menu_in));
        containerView.setVisibility(VISIBLE);
        containerView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim
                .anim_mask_in));
        popupMenuViews.addView(view);
    }

    public void notifyMenuItemChange(int index, boolean isShow) {
        if (index < 0 || index >= tabs.size()) {
            return;
        }
        BaseMenuTabView tabView = tabs.get(index);
        if (tabView != null) {
            tabView.onChange(isShow);
        }
    }

}